<template>
  <div class="app-container">
    <div ref="chart" style="width: 100%; height: 500px;"></div>
  </div>
</template>

<script setup>
import { ref, onMounted } from 'vue';
import * as echarts from 'echarts';
import { listStore } from '@/api/store/store';
import { listOutbound } from '@/api/outbound/outbound';

const chart = ref(null);

// 获取并处理数据
const fetchData = async () => {
  // 获取入库数据（假设生产日期近似入库时间）
  const { rows: inData } = await listStore({ pageSize: 1000 });
  // 获取出库数据
  const { rows: outData } = await listOutbound({ pageSize: 1000 });

  // 按日期聚合数据
  const process = (data, dateKey) => {
    return data.reduce((acc, item) => {
      const date = item[dateKey]?.split('T')[0] || item[dateKey];
      if (date) {
        acc[date] = (acc[date] || 0) + (+item.stockQuantity);
      }
      return acc;
    }, {});
  };

  const inByDate = process(inData, 'storeDate');
  const outByDate = process(outData, 'outboundTime');

  // 合并日期并排序
  const allDates = [...new Set([
    ...Object.keys(inByDate),
    ...Object.keys(outByDate)
  ])].sort((a, b) => new Date(a) - new Date(b));

  // 生成系列数据
  const inSeries = allDates.map(date => inByDate[date] || 0);
  const outSeries = allDates.map(date => outByDate[date] || 0);

  return { allDates, inSeries, outSeries };
};

// 渲染图表
onMounted(async () => {
  const { allDates, inSeries, outSeries } = await fetchData();
  const myChart = echarts.init(chart.value);

  const option = {
    tooltip: { trigger: 'axis' },
    legend: { data: ['入库量', '出库量'] },
    xAxis: { type: 'category', data: allDates },
    yAxis: { type: 'value' },
    series: [
      { name: '入库量', type: 'line', data: inSeries, smooth: true },
      { name: '出库量', type: 'line', data: outSeries, smooth: true }
    ]
  };

  myChart.setOption(option);
  window.addEventListener('resize', () => myChart.resize());
});
</script>